<?php

namespace app\common\model;

use app\admin\model\Staff;
use app\common\library\Email;
use app\common\library\Sms as Smslib;
use app\common\model\Order as OrderModel;
use app\common\model\Staff as StaffModel;
use think\Db;
use think\Exception;
use think\Model;
use think\Request;
use traits\model\SoftDelete;

class Order extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];


    public function datetimeorder($where,$date)
    {
        $startTime = strtotime('00:00');
        $endTime = strtotime('23:59');

        $timeSlots = [];

        for ($time = $startTime; $time <= $endTime; $time += 60 * 60) {
            //$timeSlots[] = date('H:i', $time);
            $startOfDay = $date.' '.date('H:i:s', $time);
            $endOfDay = $date.' '.date('H:i:s', $time+60*60-1);

            $order_list = OrderModel::alias('o')
                ->join('store s','o.store_id = s.store_id')
                ->join('store_project sp','o.project_id = sp.project_id')
                ->where($where)
                ->whereTime('o.date_timestamp', 'between', [strtotime($startOfDay), strtotime($endOfDay)])
                ->field('o.*,s.store_name,sp.project_name')
                ->order('o.createtime desc')
                ->select();
            $timeSlots[] = [
                'time'=>date('H:i', $time),
                'list'=>$order_list
            ];
        }

        return $timeSlots;
    }


    public function dateorder($where,$date)
    {

        $dates = new \DateTime($date); // 也可以换成任意日期，如 'now' 表示今天

        // 获取当天的开始时间（00:00:00）
        $startOfDay = $dates->format('Y-m-d 00:00:00');

        // 获取当天的结束时间（23:59:59）
        $endOfDay = $dates->format('Y-m-d 23:59:59');

        $list = OrderModel::alias('o')
            ->join('store s','o.store_id = s.store_id')
            ->join('store_project sp','o.project_id = sp.project_id')
            ->where($where)
            //->whereTime('o.date', 'between', [$startOfDay, $endOfDay])
            ->whereTime('o.date_timestamp', 'between', [strtotime($startOfDay), strtotime($endOfDay)])
            ->field('o.*,s.store_name,sp.project_name')
            ->order('o.createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        foreach ($list as $k=>$v){
            if ($v['staff_id']){
                $staff = User::get($v['staff_id']);
                $list[$k]['staff_name'] = $staff['nickname'];
            }
        }

        return $list;
    }

    //支付页信息
    public function paydata($order_id)
    {
        $info = OrderModel::get($order_id);

        $project = StoreProject::get($info['project_id']);

        $suborder = Suborder::alias('so')
            ->join('store_project sp','so.project_id = sp.project_id')
            ->where(['so.order_id'=>$order_id])
            ->field('so.num,sp.price,sp.project_name')
            ->select();
        $total_suborder_price = 0;

        foreach ($suborder as $k=>$v){
            $total_price =  bcmul($v['num'],$v['price'],2);
            $total_suborder_price+=$total_price;
            $suborder[$k]['total_price'] =  $total_price;
        }

        $data = [
            'project_name'=>$project['project_name'],
            'num'=>$info['num'],
            'price'=>$project['price'],
            'suborder'=>$suborder,
            'total_order_price' => bcmul($info['num'],$project['price'],2),
            'total_suborder_price'=>$total_suborder_price
        ];

        return $data;
    }

    //订单列表
    public function lists($where)
    {
        $list = OrderModel::alias('o')
            ->join('store s','o.store_id = s.store_id')
            ->join('store_project sp','o.project_id = sp.project_id')
            ->join('user su','o.staff_id = su.id','left')
            ->where($where)
            ->field('o.*,s.store_name,sp.project_name,su.nickname as staff_name')
            ->order('o.createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        foreach ($list as $k=>$v){
            $list[$k]['suborder'] = Suborder::alias('o')
                ->join('store_project sp','o.project_id = sp.project_id')
                ->where(['o.order_id'=>$v['order_id']])
                ->field('o.*,sp.project_name')->select();
        }

        return $list;
    }

    //订单详情
    public function info($order_id)
    {
        $info = OrderModel::get($order_id);

        if ($info['staff_id']){
            $staff = User::where(['id'=>$info['staff_id']])->field('id,nickname,avatar,service_status')->find();
            $info['staff_info'] = $staff;
        }

        $info['suborder'] = Suborder::alias('o')
            ->join('store_project sp','o.project_id = sp.project_id')
            ->where(['o.order_id'=>$order_id])
            ->field('o.*,sp.project_name')->select();

        $info['store_project'] = StoreProject::get($info['project_id']);

        $info['store'] = Store::get($info['store_id']);

        return $info;
    }

    //支付
    public function pay($order_id,$cash_price,$gift_card_tip_price,$swiping_card_price,$swiping_card_tip_price,$gift_card_price)
    {
        $info = OrderModel::get($order_id);
        $info->cash_price = $cash_price;
        $info->gift_card_tip_price = $gift_card_tip_price;
        $info->swiping_card_price = $swiping_card_price;
        $info->swiping_card_tip_price = $swiping_card_tip_price;
        $info->gift_card_price = $gift_card_price;
        $info->pay_status = 1;
        $info->is_hang = 0;
        $info->pay_time = time();
        $res = $info->save();

        return $res;
    }

    //快捷开单-门店
    public function fastOpenOrder($data)
    {
        $model = new Order();

        $order_data = [
            'store_id'=>$data['store_id'],
            'project_id'=>$data['project_id'],
            'num'=>$data['num'],
            'order_no'=>$this->order_no(),
            //'staff_id'=>$data['staff_id'],
        ];
        if ($data['type']==0){
            //快捷
            $order_data['order_status'] = 1;
            $order_data['order_status_name'] = '服务中';
            $order_data['is_confirm'] = 1;
            $order_data['confirm_time'] = time();
            $order_data['is_start'] = 1;
            $order_data['start_time'] = time();
            $order_data['allot_time'] = time();
            $order_data['date'] = date('Y-m-d H:i',time());
            $order_data['date_timestamp'] = time();
            $order_data['staff_id'] = $data['staff_id'];
        } else {
            //预约
            $order_data['date'] = $data['date'];
            $order_data['date_timestamp'] = strtotime($data['date']);
            $order_data['last_name'] = $data['last_name'];
            $order_data['first_name'] = $data['first_name'];
            $order_data['phone'] = $data['phone'];
            $order_data['email'] = $data['email'];
            $order_data['remark'] = $data['remark'];
            $order_data['order_status_name'] = '未开始';
        }

        $res = $model->save($order_data);
        if ($res&&$data['type']==0){
            //记录下钟时间
            $staff_model = new User();
            $staff_model->editServiceStatus($model->order_id,$data['staff_id']);
        }
        return $res;
    }


    //快捷开单-技师
    public function staffFastOpenOrder($data,$staff_id)
    {

        $model = new Order();

        $order_data = [
            'store_id'=>$data['store_id'],
            'project_id'=>$data['project_id'],
            'date'=>date('Y-m-d H:i',time()),
            'date_timestamp'=>time(),
            'num'=>$data['num'],
            'order_no'=>$this->order_no(),
            'staff_id'=>$staff_id,
            'allot_time'=>time(),
            'is_start'=>1,
            'start_time'=>time(),
            'is_confirm'=>1,
            'confirm_time'=>time(),
            'order_status'=>1,
            'order_status_name'=>'服务中'
        ];

        $res = $model->save($order_data);
        if ($res){
            //记录下钟时间
            $staff_model = new User();
            $staff_model->editServiceStatus($model->order_id,$staff_id);
        }
        return $res;
    }

    public function cancel($order_id,$type=0)
    {
        Db::startTrans();
        try {
            $info = OrderModel::get($order_id);
            if (!$info)throw new Exception('订单不存在');
            if ($info->is_cancel == 1)throw new Exception('订单已取消');
            $info->cancel_type = $type;
            $info->is_cancel = 1;
            $info->cancel_time = time();
            $info->order_status = -1;
            $info->order_status_name = '已取消';
            $info->save();

            $store = \app\admin\model\Store::get($info['store_id']);
            $project = StoreProject::get($info['project_id']);
            //$message_title = \app\common\model\Config::get(['name'=>'submit_title'])->value;
            $message_title = '预约项目取消成功';
            $request = Request::instance();
            $domain=$request->domain();
            $url = $domain.'/dist/#/complete?order_id='.$order_id;

            $ret = Smslib::send($info->phone, null, 'add',$store['store_name'],$project['project_name'],$info->date,$store['address']);
            if (!$ret) {
                Db::rollback();
                throw new Exception('发送失败，请检查短信配置是否正确');
            }

            $content = '<!DOCTYPE html>
                <html lang="en">
                <head>
                   <meta charset="UTF-8">
                   <meta name="viewport" content="width=device-width, initial-scale=1.0">
                   <title>Appointment Confirmation</title>
                </head>
                <body style="margin: 0; padding: 0;">
                   <table width="100%" cellspacing="0" cellpadding="0">
                      <tr>
                         <td align="center" valign="top" style="padding: 10px;">
                            <table width="100%" max-width="600" cellspacing="0" cellpadding="0">
                               <tr>
                                  <td align="center" style="font-size: 20px; margin-bottom: 30px; padding: 10px 0;">Appointment Scheduled</td>
                               </tr>
                               <tr>
                                  <td style="box-shadow: 0 0 8px 0 #0000001a; padding: 18px 14px; box-sizing: border-box;">
                                     <table width="100%" cellspacing="0" cellpadding="0">
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">What</td>
                                           <td>'.$project['project_name'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="16"></td>
                                        </tr>
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">When</td>
                                           <td>'.$info['date'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="16"></td>
                                        </tr>
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">Where</td>
                                           <td style="word-break: break-word;">'.$store['address'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="20" colspan="2"></td>
                                        </tr>
                                        <tr>
                                           <td colspan="2" align="center" style="color: #A1A1A1; font-size: 14px; text-align: center; padding: 0 5%;">Thank you, your appointment has been successfully scheduled.</td>
                                        </tr>
                                     </table>
                                  </td>
                               </tr>
                   
                               <tr>
                                  <td align="center" valign="middle" style="padding: 30px 0 10px; text-align: center;">
                                     <!--[if mso]>
                                                      <table align="center" border="0" cellspacing="0" cellpadding="0">
                                                      <tr><td>
                                                      <![endif]-->
                                     <a href="'.$url.'"
                                        style="display: block; width: 227px; height: 54px; opacity: 1; background: #030302; color: #fff; line-height: 54px; text-align: center; font-size: 12px; text-decoration: none; margin: 0 auto;">Change/Cancel
                                        Appointment</a>
                                     <!--[if mso]>
                                                      </td></tr>
                                                      </table>
                                                      <![endif]-->
                                  </td>
                               </tr>
                            </table>
                         </td>
                      </tr>
                   </table>
                </body>
                </html>';
            $email = new Email;
            $result = $email
                ->to($info['email'])
                ->subject($message_title)
                ->message($content)
                ->send();

            if (!$result) {
                throw new Exception('邮箱发送失败');
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            throw new Exception('取消失败');
        }
    }


    public function order_no(){
        $order_no = null;
        while (true) {
            $order_no = date('YmdHis') . mt_rand(1000, 9999);
            $exist_order_no = OrderModel::get(['order_no' => $order_no]);
            if (!$exist_order_no) {
                break;
            }
        }
        return $order_no;
    }
}
